package com.uenpay.im.ui.old.activity.login;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.telephony.PhoneNumberUtils;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.utils.Utils;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.PushServiceConn;
import com.uenpay.im.ui.old.activity.TabMenuActivity;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.invokeitems.HttpPostRequest;
import com.uenpay.im.serializations.QYXUserSerializer;
import com.uenpay.im.utilities.PhoneUtils;
import com.uenpay.util.app.base.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author SL
 * @Description 注册
 * @CopyRight http://www.qiyunxin.com
 */
public class RegisterActivity extends BaseActivity {

	private View loading;
	private EditText account_edit, pwd_edit, verification_code_edit, nick_name_et;
	private Button register_btn, get_verification_code_btn;
	private boolean is_register = true;
	private LoginAndRegisterHandle loginAndRegisterHandle = new LoginAndRegisterHandle();
	private RelativeLayout name_layout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		isFullScreen = true;
		super.onCreate(savedInstanceState);
	}

	@Override
	public View bindView() {
		return null;
	}

	@Override
	public int bindLayout() {
		return R.layout.activity_register_layout;
	}

	@Override
	public void initView(View view) {
		is_register = getIntent().getBooleanExtra("is_register", true);
		initView();
		initListener();
	}

	protected void initView() {
		name_layout = (RelativeLayout) findViewById(R.id.name_layout);
		loading = findViewById(R.id.loading);
		((TextView) findViewById(R.id.title_textview)).setText(getResources().getString(R.string.register));
		account_edit = (EditText) findViewById(R.id.account_edit);

		pwd_edit = (EditText) findViewById(R.id.pwd_edit);
		verification_code_edit = (EditText) findViewById(R.id.verification_code_edit);
		nick_name_et = (EditText) findViewById(R.id.nick_name_et);
		register_btn = (Button) findViewById(R.id.register_btn);
		get_verification_code_btn = (Button) findViewById(R.id.get_verification_code_btn);
		if (!is_register) {
			((TextView) findViewById(R.id.title_textview)).setText(getResources().getString(R.string.reset_pwd));
			register_btn.setText(getResources().getString(R.string.sure));
			name_layout.setVisibility(View.GONE);
		}
	}

	protected void initListener() {
		nick_name_et.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				String content = nick_name_et.getText().toString();
				if (Utils.String_length(content) > 30) {
					if (content.length() > 15) {
						nick_name_et.setText(content.substring(0, 15));
						nick_name_et.setSelection(nick_name_et.getText().toString().length());
					}
					return;
				}
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			}

			@Override
			public void afterTextChanged(Editable arg0) {
			}
		});

		register_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				String account_name = account_edit.getText().toString();
				String nick_name = nick_name_et.getText().toString();
				String account_pwd = pwd_edit.getText().toString();
				String verification_code = verification_code_edit.getText().toString();
				if (!TextUtils.isEmpty(account_name) && !TextUtils.isEmpty(account_pwd) && !TextUtils.isEmpty(verification_code)) {

					if (!checkPwdLength(account_pwd)) {
						IMApplication.showToast(getResources().getString(R.string.pwd_length));
						return;
					}
					boolean mat = account_pwd.matches("^(\\s|.*\\s+.*)$");
					if (mat) {
						IMApplication.showToast(getResources().getString(R.string.phone_and_pwd_not_null));
						return;
					}
					if (account_pwd.getBytes().length != account_pwd.length()) {
						IMApplication.showToast(getResources().getString(R.string.pwd_can_not_contain_chinese_characters));
						return;
					}
					if (is_register && !TextUtils.isEmpty(nick_name)) {

						if (account_name.startsWith("1") && account_name.length() == 11) {
							register(nick_name, account_name, account_pwd, verification_code);
							// register(account_name, account_pwd, nick_name,
							// verification_code);
						} else {
							IMApplication.showToast(getResources().getString(R.string.phone_number_error));
							return;
						}
					} else {
						updatePwd(account_name, verification_code, account_pwd);
					}
				} else {
					chekInfo(account_name, verification_code, account_pwd);
				}
			}
		});
		get_verification_code_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				String account_name = account_edit.getText().toString();
				if (!TextUtils.isEmpty(account_name)) {

					boolean isphone=PhoneUtils.isMobile(account_name);
					if (isphone){
						if (is_register) {
							CheckMobileIsRegister(account_name);
						} else {
							// TODO
							getRegisterCaptcha(account_name);
						}
					}else {
						IMApplication.showToast(getResources().getString(R.string.phone_number_error));
						return;
					}


				} else {
					IMApplication.showToast("手机号不能为空");
				}

			}
		});
	}

	/**
	 * 获取验证码
	 *
	 * @param phoneNum
	 */
	private void getRegisterCaptcha(String phoneNum) {
		loading.setVisibility(View.VISIBLE);
		loginAndRegisterHandle.getRegisterCaptcha(phoneNum, "register", new LoginAndRegisterHandle.IRegisterCaptchaResultListener() {

			@Override
			public void onRegisterCaptchaResult(int status, String msg, String vercode) {
				myHandler.sendEmptyMessage(0);
				if (status == HttpInvokeResultCode.RESULT_OK) {
					// verification_code_edit.setText(vercode);
					if (timer != null) {
						timer.start();
					}
					get_verification_code_btn.setEnabled(false);
					get_verification_code_btn.setBackgroundResource(R.drawable.btn_gaincode_selector);
				} else {
					if (!TextUtils.isEmpty(msg))
						IMApplication.showToast(msg);
				}
			}
		});

	}

	/**
	 * @param mobile_phone
	 * @param pwd
	 * @param phone_validate_code
	 */
	private void register(String userName, final String mobile_phone, final String pwd, final String phone_validate_code) {
		loading.setVisibility(View.VISIBLE);

		try {
			String url = APIConfiguration.getServiceBaseUrl() + "users/?code=" + phone_validate_code + "&type=mobile";
			JSONObject dataJson = new JSONObject();
			dataJson.put("nickname", userName);
			dataJson.put("mobile", mobile_phone);
			dataJson.put("password", pwd);
			HttpPostRequest.onRequest(url, dataJson.toString(), HttpPostRequest.REQUESTMETHOD_POST, new HttpPostRequest.IRequest() {
				@Override
				public void onResult(int responseCode, String response) {
					Message msg = myHandler.obtainMessage();
					msg.what = 0;
					myHandler.sendMessage(msg);
					Log.e("注册返回结果：", response);
					if (responseCode == 200) {
						JSONObject js = null;
						try {
							js = new JSONObject(response);
							IMApplication.getInstance().setLoginInfo(js.optString("custid"), js.optString("token"), js.optString("auth"));
							IMApplication.getInstance().setUcrToken(js.optString("ucrtoken"));
							IMApplication.getInstance().setUcrOpenId(js.optString("ucropenid"));
							QYXUserSerializer.deserializeUser(js);

							PushServiceConn.getInstance(RegisterActivity.this).startConn();
							Intent intent = new Intent(RegisterActivity.this, TabMenuActivity.class);
							startActivity(intent);
							finish();
						} catch (JSONException e) {
							e.printStackTrace();
						}

					} else {
						if (!TextUtils.isEmpty(response)) {
							JSONObject j = null;
							try {
								j = new JSONObject(response);
								IMApplication.showToast(j.optString("err_msg"));
							} catch (JSONException e) {
								e.printStackTrace();
							}

						}
					}
				}
			});
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	//
	// /**
	// * 注册
	// *
	// * @param mobile_phone
	// * @param pwd
	// * @param phone_validate_code
	// */
	// private void register(final String mobile_phone, final String pwd,
	// final String nickname, final String phone_validate_code) {
	// loading.setVisibility(View.VISIBLE);
	//
	// loginAndRegisterHandle.registerApp(mobile_phone, pwd, nickname,
	// phone_validate_code, new LoginAndRegisterHandle.ILoginResultListener() {
	//
	// @Override
	// public void onLoginResult(int status, String msg,
	// QYXUserEntity mQyxUserEntity) {
	// myHandler.sendEmptyMessage(0);
	// if (status == HttpInvokeResultCode.RESULT_OK) {
	// if (mQyxUserEntity != null
	// && (mQyxUserEntity.status == 1 || mQyxUserEntity.status ==
	// HttpInvokeResultCode.RESULT_OK)) {
	// PushServiceConn.getInstance(
	// RegisterActivity.this).startConn();
	// Intent intent = new Intent(
	// RegisterActivity.this,
	// TabMenuActivity.class);
	// startActivity(intent);
	// finish();
	// }
	// } else {
	// IMApplication.showToast(msg);
	// }
	// }
	// });
	// }

	/**
	 * 修改密码
	 *
	 * @param mobile_phone
	 * @param phone_validate_code
	 * @param new_password
	 */
	private void updatePwd(String mobile_phone, String phone_validate_code, String new_password) {
		loading.setVisibility(View.VISIBLE);

		loginAndRegisterHandle.resetPwd(mobile_phone, phone_validate_code, new_password,
				new LoginAndRegisterHandle.IResetPwdResultListener() {

					@Override
					public void onResult(int status, String msg) {
						myHandler.sendEmptyMessage(0);
						if (!TextUtils.isEmpty(msg)) {
							IMApplication.showToast(msg);
						}
						if (status == HttpInvokeResultCode.RESULT_OK) {
							// TODO: 2017/5/15 注册页面移植
							// Intent intent = new Intent(RegisterActivity.this,
							// LoginActivity.class);
							// startActivity(intent);
						}
					}
				});

	}

	/**
	 * 检查手机号是否注册
	 *
	 * @param mobile_phone
	 */
	private void CheckMobileIsRegister(final String mobile_phone) {
		loading.setVisibility(View.VISIBLE);
		loginAndRegisterHandle.checkMobileIsRegister(mobile_phone, new LoginAndRegisterHandle.IResetPwdResultListener() {

			@Override
			public void onResult(int status, String msg) {
				myHandler.sendEmptyMessage(0);
				if (status == HttpInvokeResultCode.RESULT_OK) {
					getRegisterCaptcha(mobile_phone);
				} else {
					IMApplication.showToast(msg);
				}
			}
		});
	}

	private Handler myHandler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message arg0) {
			if (arg0.what == 0) {
				if (loading != null)
					loading.setVisibility(View.GONE);
			}
			return false;
		}
	});

	CountDownTimer timer = new CountDownTimer(60 * 1000, 1000) {
		@Override
		public void onTick(long millisUntilFinished) {
			get_verification_code_btn.setText(getResources().getString(R.string.send_code) + "(" + (millisUntilFinished / 1000) + ")");
		}

		@Override
		public void onFinish() {
			get_verification_code_btn.setEnabled(true);
			// sendButtom.setTextColor(getResources().getColor(R.color.white));
			get_verification_code_btn.setBackgroundResource(R.drawable.btn_gaincode_selector);
			get_verification_code_btn.setText(getResources().getString(R.string.send_code));
		}

	};

	private void chekInfo(String name, String code, String pwd) {
		if (TextUtils.isEmpty(name)) {
			IMApplication.showToast(getResources().getString(R.string.phone_number_error));
			return;
		} else if (TextUtils.isEmpty(code)) {
			IMApplication.showToast(getResources().getString(R.string.phone_number_error));
			IMApplication.showToast(getResources().getString(R.string.code_number_not_null));
			return;
		} else if (TextUtils.isEmpty(pwd)) {
			IMApplication.showToast(getResources().getString(R.string.pwd_not_null));
			return;
		}
	}

	/**
	 * 检查密码长度
	 *
	 * @param pwd
	 * @return
	 */
	private boolean checkPwdLength(String pwd) {
		if (pwd.length() < 6 || pwd.length() > 16) {
			return false;
		} else {
			return true;
		}
	}
}
